package com.leyou.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.utils.RegexUtils;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.service.UserService;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.leyou.common.constants.MQConstants.ExchangeConstants.SMS_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.RoutingKeyConstants.VERIFY_CODE_KEY;


@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Override
    public Boolean checkExists(String data, Integer type) {

        if (StringUtils.isEmpty(data) || (2 == type && !RegexUtils.isPhone(data))) {
            throw new LyException(400, "请求参数有误");
        }

        String colName = null;
        switch (type) {
            case 1:
                colName = "username";
                break;
            case 2:
                colName = "phone";
                break;
                default:
                    throw new LyException(400, "请求参数有误");
        }
        return query().eq(colName, data).count() == 1;
    }

    @Autowired
    private AmqpTemplate amqpTemplate;

    /**
     *  这里用stringRedisTemplate 是直接声明了这个模板存入 redis中的键值对是 对应<string,string>类型
     *  省去了后边定义键值对类型的麻烦
     *  所以注入StringRedisTemplate到spring容器中
     */
    @Autowired
    private StringRedisTemplate redisTemplate;

    private final String KEY_PREFIX = "user:verify:code:";
    @Override
    public void sendMsg(String phone) {
        if (!RegexUtils.isPhone(phone)) {
            throw new LyException(400, "请求参数有误");
        }

        Map<String, String> msg = new HashMap<>();
        msg.put("phone",phone);
        String code = RandomStringUtils.randomNumeric(6);
        msg.put("code", code);

        this.amqpTemplate.convertAndSend(SMS_EXCHANGE_NAME,VERIFY_CODE_KEY,msg);
        redisTemplate.opsForValue().set(KEY_PREFIX+phone,code,5, TimeUnit.MINUTES);
    }

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public void UserRegister(User user, String code) {
        String key = KEY_PREFIX + user.getPhone();


        //输入验证码时，还有效，到后台还有效，到了业务无效
        if (StringUtils.isEmpty(code) || !redisTemplate.hasKey(key) || !code.equals(redisTemplate.opsForValue().get(key))) {
            throw new LyException(400, "验证码输入有误");
        }
        //通过spring自带的加密 加载干扰因子
        String encodePassword = passwordEncoder.encode(user.getPassword());
        //替换密码
        user.setPassword(encodePassword);

        //存入redis
        save(user);

        //登录 根据秘闻推测 ,盐值, 使用盐值和密码再次加密,用加密后的密码和获取的encodePassword做比较
       // this.passwordEncoder.matches(user.getUsername(), user.getPassword());

    }

    @Override
    public UserDTO queryUserByNameAndPass(String username, String password) {
        User user = query().eq("username", username).one();

        //user为空  或者 密码匹配失败
        if (null == user || !passwordEncoder.matches(password, user.getPassword())) {

            throw new LyException(400, "用户名或密码错误");
        }

        //两种返回UserDTO的方法 第一种自己定义的
        return BeanHelper.copyProperties(user,UserDTO.class);
        //return new UserDTO(user);
    }
}